package cn.dida.core;

import cn.dida.model.Sysres;
import cn.dida.service.SysresService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 系统初始化程序
 * @author weiwei 
 */
public class SystemInitializer {

    private Log logger = LogFactory.getLog(SystemInitializer.class);
    private ApplicationContext applicationContext;

    public SystemInitializer(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void init() throws Exception {
        initResTree();
    }

    public void initResTree() {
        logger.info("初始化资源树");
        try {
            SysresService sysresService = applicationContext.getBean(SysresService.class);
            List<Sysres> allSysres = sysresService.getAllEnableSysres();
            ArrayList<Sysres> resTree = new ArrayList<>();
            ArrayList<Sysres> resNodes = new ArrayList<>();

            resNodes.addAll(allSysres);
            resTree.addAll(SysresMap.makeTree(allSysres));

            //排序
            Collections.sort(resTree, (Comparator<Sysres>) (o1, o2) -> {
                if (o1.getNo() != null || o2.getNo() != null) {
                    if (o1.getNo() == null) {
                        return 1;
                    } else if (o2.getNo() == null) {
                        return -1;
                    } else {
                        return o1.getNo().compareTo(o2.getNo());
                    }
                }
                return 0;
            });
            SysresMap.init(resTree, resNodes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
